package com.example.minio_demo.service;

import com.example.minio_demo.config.MinioConfig;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import jakarta.annotation.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author TonySong
 * @date 2025/8/9 0009
 * @time 17:20
 */
@Service
public class MinioService {
    @Resource
    private MinioConfig minioConfig;

    @Resource
    private MinioClient minioClient;

    public String upload(MultipartFile file) throws Exception {
        //检测存储桶是否存在，如果不存在则创建
        if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucket()).build())){
            minioClient.makeBucket(MakeBucketArgs.builder().build());
        }
        String originalFilename = file.getOriginalFilename();
        String fileExtension=originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = UUID.randomUUID().toString()+fileExtension;

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConfig.getBucket())
                        .object(objectName)
                        .stream(file.getInputStream(),file.getSize(),-1)
                        .contentType(file.getContentType())
                        .build());

        return objectName;
    }

    public String getFileUrl(String objectName,int expireTime) throws Exception {
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(minioConfig.getBucket())
                        .object(objectName)
                        .expiry(expireTime, TimeUnit.MINUTES)
                        .build());
    }

    public void removeFile(String objectName) throws Exception {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(minioConfig.getBucket())
                        .object(objectName)
                        .build()
        );
    }

}
